package com.hd.crdao.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hd.crdao.MainActivity;
import com.hd.crdao.R;
import com.hd.crdao.adapter.MyViewPagerAdapter;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.base.MyApplication;
import com.hd.crdao.base.MyBaseAdapter;
import com.hd.crdao.bean.CarDetailInfoBean;
import com.hd.crdao.bean.CarMark;
import com.hd.crdao.bean.CarPlateBean;
import com.hd.crdao.bean.CarVinRecognizeBean;
import com.hd.crdao.bean.ImagePathBean;
import com.hd.crdao.bean.MessageBean;
import com.hd.crdao.bean.MsgBean;
import com.hd.crdao.bean.ReleaseCityBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.proxy.RecognizeService;
import com.hd.crdao.proxy.SimpleTextChangeWatcher;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.ChineseUtils;
import com.hd.crdao.utils.FileUtils;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.AllCapTransformationMethod;
import com.hss01248.dialog.StyledDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Administrator
 *@date 2017/5/12 0012
 */
public class ReleaseActivity extends BaseActivity {
    private static final int UPLOADPICTURES = 121;
    private static final int REQUEST_CODE_LICENSE_PLATE = 122;
    private static final int REQUEST_CODE_GENERAL_WEBIMAGE = 123;
    private static final int REQUEST_GRANTED_PERMISSIONS_CODE = 124;
    public TimePickerView mTimePickerView;
    public InputMethodManager mImm;
    public String mThirdid;
    public String mVinCode;
    public String mPlateNumber;
    public String mBrand;
    public String mFailTime;
    public String mMileage;
    public String mPrice;
    public String mColor;
    public String mTransferTimes;
    public String mUseProperty;
    public String mMainTain;
    public String mPlateArea;
    public String mInsurance;
    public String mCarCheck;
    public String mBusInsurance;
    public String mDescribe;
    @BindView(R.id.release_head)
    ExpandHeadView mReleaseHead;
    @BindView(R.id.iv_picture)
    ImageView mIvPicture;
    @BindView(R.id.rl_photo)
    RelativeLayout mRlPhoto;
    @BindView(R.id.vp_photo)
    ViewPager mVpPhoto;
    @BindView(R.id.et_vin)
    EditText mEtVin;
    @BindView(R.id.rl_vin)
    RelativeLayout mRlVin;
    @BindView(R.id.et_number)
    EditText mEtNumber;
    @BindView(R.id.rl_number)
    RelativeLayout mRlNumber;
    @BindView(R.id.tv_brand)
    TextView mTvBrand;
    @BindView(R.id.rl_brand)
    RelativeLayout mRlBrand;
    @BindView(R.id.tv_time)
    TextView mTvTime;
    @BindView(R.id.rl_time)
    RelativeLayout mRlTime;
    @BindView(R.id.et_mileage)
    EditText mEtMileage;
    @BindView(R.id.rl_mileag)
    RelativeLayout mRlMileag;
    @BindView(R.id.et_price)
    EditText mEtPrice;
    @BindView(R.id.rl_price)
    RelativeLayout mRlPrice;
    @BindView(R.id.tv_color)
    TextView mTvColor;
    @BindView(R.id.rl_color)
    RelativeLayout mRlColor;
    @BindView(R.id.tv_transfer)
    TextView mTvTransfer;
    @BindView(R.id.rl_transfer)
    RelativeLayout mRlTransfer;
    @BindView(R.id.tv_nature)
    TextView mTvNature;
    @BindView(R.id.rl_nature)
    RelativeLayout mRlNature;
    @BindView(R.id.tv_baoyang)
    TextView mTvBaoyang;
    @BindView(R.id.rl_baoyang)
    RelativeLayout mRlBaoyang;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    @BindView(R.id.rl_address)
    RelativeLayout mRlAddress;
    @BindView(R.id.tv_safe)
    TextView mTvSafe;
    @BindView(R.id.rl_safe)
    RelativeLayout mRlSafe;
    @BindView(R.id.tv_check)
    TextView mTvCheck;
    @BindView(R.id.rl_check)
    RelativeLayout mRlCheck;
    @BindView(R.id.tv_syx)
    TextView mTvSyx;
    @BindView(R.id.rl_syx)
    RelativeLayout mRlSyx;
    @BindView(R.id.et_des)
    EditText mEtDes;
    @BindView(R.id.rl_des)
    RelativeLayout mRlDes;
    @BindView(R.id.save)
    Button mSave;
    @BindView(R.id.release)
    Button mRelease;
    @BindView(R.id.vpShow)
    FrameLayout mVpShow;
    @BindView(R.id.recognizePlate)
    ImageView mRecognizePlate;
    @BindView(R.id.recognizeVin)
    ImageView mRecognizeVin;
    private String carInfoId; //车辆信息ID
    public SimpleTextChangeWatcher simpleTextChangeWatcher;
    /**
     * 当为true 表示是从主页过来  false表示是从其他页面跳转过来的 eg:我的车源等
     */
    public boolean isFromMain;
    public List<CarMark> carMarks;
    private ArrayList<String> mImagePaths = new ArrayList<>();
    public String carid;
    public int state;
    public MyViewPagerAdapter myViewPagerAdapter;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == UPLOADPICTURES) {
                ALog.d("发送的消息已经收到 !~");
                StyledDialog.dismissLoading();
                startActivity(new Intent(UIUtils.getContext(), MainActivity.class));
                MyToast.show("上传图片成功");
                finish();
            }
            return true;
        }
    });
    public OCR mOCR;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_release;
    }

    @Override
    protected void initView() {
        isFromMain = getIntent().getBooleanExtra("isFromMain", true);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        loadLocalFile();
        simpleTextChangeWatcher = new SimpleTextChangeWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                matchParams();
                super.afterTextChanged(editable);
            }
        };
        mEtNumber.addTextChangedListener(simpleTextChangeWatcher);
        initOCR();
    }

    /**
     * 加载本地文件到内存中
     * 根据车牌号输入自动显示所在地
     */
    private void loadLocalFile() {
        carMarks = analysisJson();
        ALog.d(carMarks.toString());
    }

    /**
     * 把资源文件转换成字符串形式
     *
     * @return 返回一个集合
     */
    public List<CarMark> analysisJson() {
        //得到本地json文本内容
        String localFile = UIUtils.getLocalFile(this, "carcode.json");
        //json转换为集合
        return new Gson().fromJson(localFile, new TypeToken<List<CarMark>>() {
        }.getType());
    }

    /**
     * 匹配输入的车牌号所在地
     */
    private void matchParams() {
        String content = mEtNumber.getText().toString().trim().toUpperCase();
        for (int i = 0; i < carMarks.size(); i++) {
            CarMark carMark = carMarks.get(i);
            String code = carMark.getCode();
            if (TextUtils.equals(code, content)) {
                ALog.d(code);
                mTvAddress.setText(carMark.getCity());
                return;
            }
        }
        if (TextUtils.isEmpty(mTvAddress.getText().toString())) {
            mTvAddress.setText(SPUtils.getString(Config.cbLocAddress, "请填写"));

        }

    }

    @Override
    protected void initListener() {
        mReleaseHead.getLeftArrowLL().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mReleaseHead.getHeadViewRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UIUtils.getContext(), MyCarSourceActivity.class));
            }
        });

        mEtVin.setTransformationMethod(new AllCapTransformationMethod());
        mEtNumber.setTransformationMethod(new AllCapTransformationMethod());

    }

    @Override
    protected void initData() {
        mTvBrand.setText(getIntent().getStringExtra("vcTypenme"));
        carid = getIntent().getStringExtra("carid");
        String setState = getIntent().getStringExtra("state");
        state = TextUtils.isEmpty(setState) ? 0 : Integer.parseInt(setState);
        if (!TextUtils.isEmpty(carid)) {
            loadCarInfo(carid);
        }
        isDisplayViewPager(false);
    }

    /**
     * 加载发布车辆信息
     *
     * @param carid
     */
    private void loadCarInfo(final String carid) {
        OkHttpUtils.post().url(Constants.GETCARINFO_URL)
                .addParams("appFlag", "true")
                .addParams("id", carid)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                CarDetailInfoBean carDetailInfoBean = new Gson().fromJson(response, CarDetailInfoBean.class);
                if (carDetailInfoBean.getSuccess() == 0) {
                    CarDetailInfoBean.CarInfoBean carInfoBean = carDetailInfoBean.getCarInfo();
                    setSomeParams(carInfoBean);
                } else {
                    MyToast.show(carDetailInfoBean.getMessage());
                }
            }
        });
    }

    /**
     * 如果是从我发布的车源页面跳转的话 , 需要手动设置一些参数
     *
     * @param carInfoBean
     */
    private void setSomeParams(CarDetailInfoBean.CarInfoBean carInfoBean) {
        setParam(mEtVin, carInfoBean.getCiVin());
        setParam(mEtNumber, carInfoBean.getCiPlate());
        if (carInfoBean.getVehConfig() != null) {
            setParam(mTvBrand, carInfoBean.getVehConfig().getVcTypenme());
        }
        setParam(mTvTime, carInfoBean.getCiFailtime());
        setParam(mEtMileage, carInfoBean.getCiClicknum() + "");
        setParam(mEtPrice, String.valueOf(carInfoBean.getCiExpectprice()));
        setParam(mTvColor, carInfoBean.getCiColour());
        setParam(mTvTransfer, "" + carInfoBean.getCiTranstimes());
        setParam(mTvNature, carInfoBean.getCiUseproperty());
        setParam(mTvBaoyang, carInfoBean.getCiMaintain());
        setParam(mTvAddress, carInfoBean.getCiPlatearea());
        setParam(mTvSafe, carInfoBean.getCiInsurance());
        setParam(mTvCheck, carInfoBean.getCiCarcheck());
        setParam(mTvSyx, carInfoBean.getCiBusinsurance());
        setParam(mEtDes, carInfoBean.getCiDescribe());

        if (carInfoBean.getPicStores() != null) {
            List<CarDetailInfoBean.CarInfoBean.PicStoresBean> picStores = carInfoBean.getPicStores();
            for (int i = 0; i < picStores.size(); i++) {
                CarDetailInfoBean.CarInfoBean.PicStoresBean picStoresBean = picStores.get(i);
                mImagePaths.add(i, Constants.IMAGEURL + picStoresBean.getPsPath());
            }
            isDisplayViewPager(true);
        }

        if (state < 3) {
            mEtVin.setFocusableInTouchMode(false);
            mEtNumber.setFocusableInTouchMode(false);
            mEtPrice.setFocusableInTouchMode(false);
            mEtDes.setFocusableInTouchMode(false);
            mEtMileage.setFocusableInTouchMode(false);
            mSave.setVisibility(View.GONE);
            mRelease.setVisibility(View.GONE);

        } else {
            mSave.setVisibility(View.VISIBLE);
            mRelease.setVisibility(View.VISIBLE);
            mEtVin.setFocusableInTouchMode(true);
            mEtNumber.setFocusableInTouchMode(true);
            mEtPrice.setFocusableInTouchMode(true);
            mEtDes.setFocusableInTouchMode(true);
            mEtMileage.setFocusableInTouchMode(true);
        }

    }

    /**
     * 设置参数
     *
     * @param key
     * @param value
     */
    public void setParam(TextView key, String value) {
        if (!TextUtils.isEmpty("" + value)) {
            key.setText(value);
        }
    }

    boolean recognizeFlag;

    @OnClick({R.id.rl_vin, R.id.rl_number, R.id.rl_brand, R.id.rl_time, R.id.rl_mileag, R.id.rl_price, R.id.rl_color,
            R.id.rl_transfer, R.id.rl_nature, R.id.rl_baoyang, R.id.rl_address,
            R.id.rl_safe, R.id.rl_check, R.id.rl_syx, R.id.rl_des, R.id.save, R.id.release, R.id.vpShow, R.id.recognizePlate, R.id.recognizeVin})
    public void onViewClicked(View view) {

        if (!TextUtils.isEmpty(carid) && state < 3) {
            return;
        }
        switch (view.getId()) {
            case R.id.rl_vin:      //Vin码
                mEtVin.requestFocus();
                showKeyBoard();

                break;
            case R.id.rl_number:  //车牌号
                mEtNumber.requestFocus();
                showKeyBoard();
                break;
            case R.id.rl_brand:   //品牌车型
                startActivity(new Intent(UIUtils.getContext(), CarType1Activity.class));
                break;
            case R.id.rl_time:   //上牌时间
                setTime(mTvTime);
                break;
            case R.id.rl_mileag:  //公里数
                mEtMileage.requestFocus();
                showKeyBoard();
                break;
            case R.id.rl_price:  //价格
                mEtPrice.requestFocus();
                showKeyBoard();
                break;
            case R.id.rl_color:  //颜色
                showPopwindow(R.array.color, mTvColor);
                break;
            case R.id.rl_transfer:  //过户次数
                showPopwindow(R.array.transfer, mTvTransfer);
                break;
            case R.id.rl_nature:  //使用性质
                showDialog(R.array.nature, mTvNature);
                break;
            case R.id.rl_baoyang:  //保养地点
                showDialog(R.array.baoyang, mTvBaoyang);
                break;
            case R.id.rl_address:   //车牌所在地
                Intent intent = new Intent(UIUtils.getContext(), AddressActivity.class);
                intent.putExtra("fromWhere", "release");
                startActivity(intent);
                break;
            case R.id.rl_safe:   //交强险到期
                setTime(mTvSafe);
                break;
            case R.id.rl_check:  //年检到期
                setTime(mTvCheck);
                break;
            case R.id.rl_syx:   //商业险
                setTime(mTvSyx);
                break;
            case R.id.rl_des:   //车主描述
                mEtDes.requestFocus();
                break;
            case R.id.save:   //保存
                if (judgeAllInfo(true)) {
                    saveAndPublish(Constants.UPDATECARINFO_URL, true);
                }
                break;
            case R.id.release: //发布
                if (judgeAllInfo(false)) {
                    saveAndPublish(Constants.SAVECARINFO_URL, false);
                }
                break;

            case R.id.vpShow:
                toGetImageFromOther();
                break;

            case R.id.recognizePlate:       //识别车牌号功能
                recognizeFlag = true;
                checkPermissions_Settings();
                break;
            case R.id.recognizeVin:
                recognizeFlag = false;
                checkPermissions_Settings();
                break;
            default:
                break;
        }
    }

    private void checkPermissions_Settings() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.System.canWrite(this)) {
                recognizeWhat();
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_GRANTED_PERMISSIONS_CODE);
            }
        } else {
            recognizeWhat();    //识别内容有车牌/vin
        }
    }

    private void recognizeWhat() {
        if (recognizeFlag) {
            recognizePlateNumber();
        } else {
            recognizeVin();
        }
    }

    /**
     * 识别Vin码
     */
    private void recognizeVin() {
        Intent intent = new Intent(UIUtils.getContext(), CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtils.getSaveFile(ReleaseActivity.this).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        startActivityForResult(intent, REQUEST_CODE_GENERAL_WEBIMAGE);
    }

    private void initOCR() {
        mOCR = OCR.getInstance();
        mOCR.initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                ALog.d(token);
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
            }
        }, UIUtils.getContext(), getString(R.string.OCR_AK), getString(R.string.OCR_SK));
    }

    /**
     * 识别车牌号--来自百度AI
     */
    private void recognizePlateNumber() {
        Intent intent = new Intent(UIUtils.getContext(), CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtils.getSaveFile(ReleaseActivity.this).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        startActivityForResult(intent, REQUEST_CODE_LICENSE_PLATE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_LICENSE_PLATE && resultCode == Activity.RESULT_OK) {
            RecognizeService.recLicensePlate(FileUtils.getSaveFile(ReleaseActivity.this).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
                            //得到的结果是什么?
                            ALog.d(result);
                            if (result.contains("log_id")) {
                                CarPlateBean carPlateBean = new Gson().fromJson(result, CarPlateBean.class);
                                mEtNumber.setText(carPlateBean.getWords_result().getNumber());
                            } else {
                                MyToast.show("识别失败");
                            }
                        }
                    });
        } else if (requestCode == REQUEST_CODE_GENERAL_WEBIMAGE && resultCode == Activity.RESULT_OK) {
            RecognizeService.recWebimage(FileUtils.getSaveFile(ReleaseActivity.this).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
                            ALog.d(result);
                            // MyToast.show(result);
                            if (result.contains("log_id")) {
                                CarVinRecognizeBean carVinRecognizeBean = new Gson().fromJson(result, CarVinRecognizeBean.class);
                                String words = carVinRecognizeBean.getWords_result().get(0).getWords();
                                String vinCode = ChineseUtils.dealWithWords(words);
                                mEtVin.setText(vinCode);
                            } else {
                                MyToast.show("识别失败");
                            }
                        }
                    });
        } else if (requestCode == REQUEST_GRANTED_PERMISSIONS_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 判断是否有WRITE_SETTINGS权限
                if (Settings.System.canWrite(this)) {
                    recognizeWhat();
                } else {
                    MyToast.show("未获取到所需要的权限");
                    return;
                }
            }


        }
    }

    /**
     * 从其他页面获取的数据
     */
    public void toGetImageFromOther() {
        Intent newintent = new Intent(UIUtils.getContext(), UpLoadPhotoActivity.class);
        if (mImagePaths.isEmpty()) {
            for (int i = 0; i < 12; i++) {
                mImagePaths.add(i, "");
            }
        }
        ALog.d("跳转到上传图片页面");
        newintent.putStringArrayListExtra("imagePaths", mImagePaths);
        ALog.d("发送过去的数据是:" + "长度为:" + mImagePaths.size() + "具体数据是:" +
                mImagePaths.toString());
        newintent.putExtra("isFromMain", isFromMain);
        startActivity(newintent);
    }

    /**
     * @param isSaveToDraft
     * @return
     */
    private boolean judgeAllInfo(boolean isSaveToDraft) {
        //vin
        mVinCode = mEtVin.getText().toString().trim().toUpperCase();
        //车牌号
        mPlateNumber = mEtNumber.getText().toString().trim().toUpperCase();
        //品牌
        mBrand = mTvBrand.getText().toString().trim();
        //上牌时间
        mFailTime = mTvTime.getText().toString().trim();        //默认是请选择
        if (TextUtils.equals("请选择", mFailTime)) {
            mFailTime = "";
        }
        //公里数
        mMileage = mEtMileage.getText().toString().trim();
        //价格
        mPrice = mEtPrice.getText().toString().trim();
        //颜色
        mColor = mTvColor.getText().toString().trim();
        if (TextUtils.equals("请选择", mColor)) {
            mColor = "";
        }
        //过户次数
        mTransferTimes = mTvTransfer.getText().toString().trim();   //默认是请选择
        if (TextUtils.equals("请选择", mTransferTimes)) {
            mTransferTimes = "";
        }
        //使用性质
        mUseProperty = mTvNature.getText().toString().trim();
        //保养地点
        mMainTain = mTvBaoyang.getText().toString().trim();
        //车牌地点
        mPlateArea = mTvAddress.getText().toString().trim();    //请填写
        if (TextUtils.equals("请填写", mPlateArea)) {
            mPlateArea = "";
        }
        //交强险到期
        mInsurance = mTvSafe.getText().toString().trim();
        //年检到期
        mCarCheck = mTvCheck.getText().toString().trim();
        //商业险
        mBusInsurance = mTvSyx.getText().toString().trim();
        //车主描述
        mDescribe = mEtDes.getText().toString().trim();
        if (isSaveToDraft) {        //是否是草稿
            if (judgeIsEmpty(mVinCode, mPlateNumber
                    , mBrand, mFailTime
                    , mMileage, mPrice
                    , mColor, mTransferTimes
                    //  , mUseProperty , mMainTain
                    , mPlateArea
                    // , mInsurance, mCarCheck  , mBusInsurance
                    , mDescribe) == 0) {
                MyToast.show("至少填写一条数据才能保存哦!~");
                return false;
            } else {
                return true;
            }

        } else {
            if (TextUtils.isEmpty(mVinCode) || TextUtils.isEmpty(mPlateNumber) ||
                    TextUtils.isEmpty(mBrand) || TextUtils.isEmpty(mFailTime) ||
                    TextUtils.isEmpty(mMileage) || TextUtils.isEmpty(mPrice) ||
                    TextUtils.isEmpty(mColor) || TextUtils.isEmpty(mTransferTimes) ||
                    TextUtils.isEmpty(mUseProperty) || TextUtils.isEmpty(mMainTain) ||
                    TextUtils.isEmpty(mMainTain) || TextUtils.isEmpty(mPlateArea) ||
                    TextUtils.isEmpty(mInsurance) || TextUtils.isEmpty(mCarCheck) ||
                    TextUtils.isEmpty(mBusInsurance) || TextUtils.isEmpty(mDescribe)
                    ) {
                MyToast.show("填写完整信息才能上传哦!~");
                return false;
            } else {
                return true;
            }
        }


    }

    /**
     * 保存或发布使用的方法
     *
     * @param url
     */
    private void saveAndPublish(String url, final boolean isSaveDragLeft) {
        String businessid = SPUtils.getString(Config.businessId, "");
        HashMap<String, String> map = new HashMap<>();
        map.put("sign", Constants.SIGN);//	sign	签名
        map.put("carBusinessId", businessid);
        if (mVinCode != null) {
            map.put("vin", mVinCode);
        }
        map.put("plate", mPlateNumber);//	plate	车牌号
        if (mThirdid != null) {
            map.put("vehConfigId", mThirdid);//	vehConfigId	车型ID
        }/*else {
            map.put("vehConfigId", "");
        }*/
        map.put("failTime", mFailTime);//	failTime	上牌时间
        map.put("mileage", mMileage);//	mileage	行驶里程
        map.put("price", mPrice);//	price	售价
        map.put("colour", mColor);//	colour	颜色
        if (!TextUtils.isEmpty(mTransferTimes)) {
            map.put("transTimes", mTransferTimes.substring(0, 1));//	transTimes	过户次数
        }
        map.put("useProperty", mUseProperty);//	useProperty	使用性质
        map.put("mainTain", mMainTain);//	mainTain	保养方式
        map.put("plateArea", mPlateArea);//	plateArea	上牌地址
        map.put("insurance", mInsurance);//	insurance	交强险到期
        map.put("carCheck", mCarCheck);//	carCheck	年检到期
        map.put("busInsurance", mBusInsurance);//	busInsurance	商业险到期
        map.put("describe", mDescribe);//	describe	车主描述
        if (!isSaveDragLeft) {        //发布至少需要上传一张图片
            if (reCountIsEmpty(mImagePaths).size() == 12) {
                MyToast.show("至少上传一张图片");
                return;
            }
        }
        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
            }

            @Override
            public void onResponse(String response, int id) {
                ALog.d(response);
                MsgBean msgBean = new Gson().fromJson(response, MsgBean.class);
                if (msgBean.getSuccess() == 0) {
                    carInfoId = msgBean.getId();
                    if (isSaveDragLeft) {       //是草稿
                        if (mImagePaths.size() > 0) {
                            upLoadImages(carInfoId);    //上传图片
                        }
                        MyToast.show(msgBean.getMessage());
                        finish();
                    } else {
                        upLoadImages(carInfoId);
                    }

                } else {
                    MyToast.show(msgBean.getMessage());

                }
            }
        });
    }

    /**
     *
     */
    public void upLoadImages(String carInfoId) {
       /* 输  入	id	车辆信息ID
        carImages	车辆照片数组
        imageId	图片ID
        imageNames	图片名称数组(非必传)
        sign	签名*/
        StyledDialog.buildMdLoading("正在上传图片中...").setActivity(this).show();

        HashMap<String, String> map = new HashMap<>();
        map.put("sign", Constants.SIGN);
        map.put("id", carInfoId);
        PostFormBuilder builder = OkHttpUtils.post()
                .url(Constants.UPLOADCARIMAGEIOS_URL);

        String[] array = getResources().getStringArray(R.array.carPicturesDesc);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mImagePaths.size(); i++) {
            String path = mImagePaths.get(i);
            if (!TextUtils.isEmpty(path)) {
                ALog.d(path);
                sb.append(array[i]).append(",");
                builder.addFile("carImages", path, new File(path));
            }
        }
        map.put("imageNames", sb.toString().substring(0, sb.toString().length() - 1));
        builder.params(map);
        builder.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("与服务器连接失败...");
                StyledDialog.dismissLoading();
            }

            @Override
            public void onResponse(String response, int id) {
                MessageBean messageBean = new Gson().fromJson(response, MessageBean.class);
                if (messageBean.getSuccess() == 0) {
                    mHandler.sendEmptyMessageDelayed(UPLOADPICTURES, 500);
                } else {
                    MyToast.show(messageBean.getMessage());
                }
            }
        });


    }


    /**
     * 弹出键盘
     */
    private void showKeyBoard() {
        mImm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        mImm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }


    /**
     * 设置车辆上牌时间
     */
    private void setTime(final TextView tv) {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(Calendar.YEAR, 1990);
        Calendar endDate = Calendar.getInstance();
        startDate.set(Calendar.YEAR, 2100);
        mTimePickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
                tv.setText(format.format(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
//                .setTitleText("Title")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
//                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLACK)//确定按钮文字颜色
                .setCancelColor(Color.BLACK)//取消按钮文字颜色
                .setTitleBgColor(0x000000)//标题背景颜色 Night mode
                .setBgColor(0x000000)//滚轮背景颜色 Night mode
                //.setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        mTimePickerView.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        mTimePickerView.show();
    }


    /**
     * @param arrayRes
     * @param textView
     */
    private void showDialog(int arrayRes, final TextView textView) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final String[] str = UIUtils.getStrings(arrayRes);
        builder.setSingleChoiceItems(str, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        textView.setText(str[which]);
                        dialog.dismiss();
                    }
                }
        ).show();
    }

    /*
    * arrayRes   数据集
    * textView   设置选择中条目的textView
    *   颜色和次数
    * */
    private void showPopwindow(int arrayRes, final TextView textView) {
        final List<String> list = new ArrayList<>();
        String[] colors = UIUtils.getStrings(arrayRes);
        Collections.addAll(list, colors);
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.color_pop_menu, null);

        ListView listView = (ListView) popView.findViewById(R.id.listview_color);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels / 2;


        final PopupWindow popWindow = getPopupWindow(parent, popView, width, height, Color.WHITE);
        listView.setAdapter(new MyBaseAdapter<String>(list) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder;
                if (convertView == null) {
                    holder = new ViewHolder();
                    convertView = View.inflate(MyApplication.getContext(), R.layout.item_pop, null);
                    //找到控件
                    holder.mTextView = (TextView) convertView.findViewById(R.id.text_pop);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                holder.mTextView.setText(list.get(position));
                return convertView;
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String s = list.get(position);
                textView.setText(s);
                popWindow.dismiss();
            }
        });

    }

    /**
     * 获取popupwindow对象
     *
     * @param parent
     * @param popView
     * @param width
     * @param height
     * @return
     */
    @NonNull
    private PopupWindow getPopupWindow(View parent, View popView, int width, int height, int color) {
        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.PopupAnimation);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        ColorDrawable dw = new ColorDrawable(color);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        return popWindow;
    }


    class ViewHolder {
        TextView mTextView;

    }

    //重写返回键
    @Override
    public void onBackPressed() {
        if (isFromMain) {
            startActivity(new Intent(UIUtils.getContext(), MainActivity.class));
            SPUtils.saveString("check", "home");
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        String vcTypenme = intent.getStringExtra("vcTypenme");
        mThirdid = intent.getStringExtra("thirdid");
        mTvBrand.setText(vcTypenme);

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (simpleTextChangeWatcher != null) {
            mEtNumber.removeTextChangedListener(simpleTextChangeWatcher);
        }
        if (mOCR != null) {
            mOCR.release();
        }
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ReciveMessage(ReleaseCityBean releaseCityBean) {
        Log.d("EventBusThread", "ThreadMode.MAIN:" + Thread.currentThread().getName());
        mTvAddress.setText(releaseCityBean.getCityName());
    }

    /**
     * 给一堆字符串,判空
     *
     * @param contents
     * @return
     */
    public int judgeIsEmpty(String... contents) {
        int count = 0;
        for (String content : contents) {
            if (!TextUtils.isEmpty(content)) {
                count++;
            }
        }
        return count;
    }

    /**
     * 是否显示ViewPager轮播图
     *
     * @param isDisplay
     */
    public void isDisplayViewPager(boolean isDisplay) {
        if (isDisplay) {
            mRlPhoto.setVisibility(View.INVISIBLE);
            mVpPhoto.setVisibility(View.VISIBLE);
            //解决中间有空值而显示的情况
            ArrayList<String> list = new ArrayList<>();
            for (int i = 0; i < mImagePaths.size(); i++) {
                if (!TextUtils.isEmpty(mImagePaths.get(i))) {
                    list.add(mImagePaths.get(i));
                }
            }
            myViewPagerAdapter = new MyViewPagerAdapter(list, this);
            mVpPhoto.setAdapter(myViewPagerAdapter);
            myViewPagerAdapter.notifyDataSetChanged();
        } else {
            mRlPhoto.setVisibility(View.VISIBLE);
            mVpPhoto.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getImageList(ImagePathBean imagePathBean) {
        mImagePaths.clear();
        ArrayList<String> list = (ArrayList<String>) imagePathBean.getList();
        if (reCountIsEmpty(list).size() == 12) {
            isDisplayViewPager(false);
        } else if (mImagePaths.size() <= 12) {
            mImagePaths.addAll(list);
            isDisplayViewPager(true);
        }
        ALog.d("回显的数据是:" + mImagePaths.toString());
    }


    /**
     * 重新统计集合中哪些是空的数据的索引集合
     *
     * @return
     */
    private ArrayList<Integer> reCountIsEmpty(ArrayList<String> targetList) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < targetList.size(); i++) {
            if (TextUtils.isEmpty(targetList.get(i))) {
                list.add(i);
            }
        }
        return list;
    }
}




